-- UISkyStoneChoose
-- Create by zouyb May/12/2016
-- 天空符石选择界面

-- UISkyStoneChoose继承自Layer
UISkyStoneChoose = class("UISkyStoneChoose", function()
    return cc.Layer:create();
end);

function UISkyStoneChoose.create(style, backForm)
    return UISkyStoneChoose.new(style, backForm);
end

-- 最大行数
local MIN_GRID_COLUMN = 4;
local MAX_GRID_ROW    = 2;
local ITEM_NAME       = "artifact";
-- 内部函数声明

-- 构造函数
function UISkyStoneChoose:ctor(style, backForm)
    self.style = style;
    self.backForm = backForm;

    -- 初始化
    self:setName("UISkyStoneChoose");
    local node = cc.CSLoader:createNode("layout/lictor/LictorChoose.csb");
    self:addChild(node);
    self.node = node;

    local CT = node:getChildByName("CT");
    self.CT = CT;
    local scroll_view = findChildByName(self.node, "CT/bg_1/scroll_view");
    self.scrollView = scroll_view;

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    self.selectIndex = 1;

    local explainLabel = findChildByName(self.CT, "bg_2/explain_scroll/explain1");
    self.pos = explainLabel:getPositionY();

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    self:initData();

    self:initGrids();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 适配
function UISkyStoneChoose:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

local function sortItem(item1, item2)
    if item1.rank < item2.rank then
        return true;
    elseif item1.rank > item2.rank then
        return false;
    end

    return item1.id > item2.id;
end

function UISkyStoneChoose:initData()
    self.data = {};

    local stoneList = SkyResourceM.getResourcesByPage("stone");
    local info = {};

    for _, stone in pairs(stoneList) do
        local tempStyle = SkyStoneM.query(stone.class_id, "style");
        if tempStyle == self.style then
            local classId = stone.class_id;

            info = ItemM.query(classId);
            local item = {};
            item.id = classId;
            item.name = info.name;
            item.rank = info.rank;
            item.desc = ItemM.getItemDetail(classId);
            item.classId = classId;
            item.amount = ItemM.getAmount(ME.user, classId);
            table.insert(self.data,item);
        end
    end

    table.sort(self.data, sortItem);
end

-- 初始化格子
function UISkyStoneChoose:initGrids(node)
    local w = DESIGN_WIDTH;
    local h = DESIGN_HEIGHT;

    -- 图标间距(横向)
    local wGap = 7;

    -- 图标间距(纵向)
    local hGap = 18;

    -- 图标宽度
    local iconWidth = 110;

    -- 图片高度
    local iconHeight = 115;

    local topHGap  = 3;
    local leftWGap = 24;
    local bottomHGap = 50;

    -- 符石列表
    local stoneList = self.data;

    -- 符石个数
    local stoneCount = #stoneList;

    self.scrollView.rows = {};
    self.scrollView:removeAllChildren();

    local itemNode = cc.CSLoader:createNode("layout/artifactt/ArtifactChooseItem.csb");
    itemNode:setScale(0.88);
    -- 初始化滚动容器内的单元格（仅针对竖向滚动容器）
    -- @param windowNode    界面节点
    -- @param scrollNode    容器节点
    -- @param itemNode      单元格的节点
    -- @param totalNum      单元格总数
    -- @param pageRowNum    单页可以显示下的行数
    -- @param maxColNum     最大列数
    -- @param wGap          单元格间距(横向) 这里作为最小值使用
    -- @param hGap          单元格间距(纵向)
    -- @param iconWidth     单元格宽度
    -- @param iconHeight    单元格高度
    -- @param topHGap       上方留白
    -- @param bottomHGap    下方留白
    -- @param leftWGap      左右留白  这里作为最小值使用
    -- @param touchEvent    点击事件注册函数
    initScrollGridsVertical(self, self.scrollView, itemNode, stoneCount, MAX_GRID_ROW, MIN_GRID_COLUMN, wGap, hGap, iconWidth, iconHeight, topHGap, bottomHGap, leftWGap, self.registerItemTouchEvent);
end

-- 显示符石选择界面
function UISkyStoneChoose:redraw()
    -- 显示标题
    local titleLabel = findChildByName(self.CT, "title/title_label");
    TextStyleM.setTitleStyle(titleLabel);
    if self.style == "revenge" then
        titleLabel:setString(getLocStr("revenge_stone_choose_title"));
    elseif self.style == "plunder" then
        titleLabel:setString(getLocStr("plunder_stone_choose_title"));
    else
        titleLabel:setString(getLocStr("explore_stone_choose_title"));
    end

    -- 绘制副标题
    local titleExplainLabel = findChildByName(self.CT, "title/title_explain");
    titleExplainLabel:setString(getLocStr("sky_stone_carry_hint"));
    TextStyleM.setSubheadStyle(titleExplainLabel);

    -- 隐藏阵营相关信息
    local campIcon = findChildByName(self.CT, "bg_2/camp_icon");
    campIcon:setVisible(false);

    local campLabel = findChildByName(self.CT, "bg_2/camp_label");
    campLabel:setVisible(false);

    -- 收集信息
    local totalGridCount = #self.data;

    -- 显示信息
    for i = 1, totalGridCount do
        local grid = self.scrollView:getChildByName("item" .. i);
        if grid then
            --  初始化格子信息
            self:initGridInfo(grid, self.data[i]);
        end
    end

    -- 初始化说明
    local btnSelect = findChildByName(self.node, "BT/choose_btn");
    if totalGridCount > 0 then
        setButtonEnabled(btnSelect, true);
        self:onItemSelected(1, 1);
    else
        setButtonEnabled(btnSelect, false);

        self:refreshExplain();
    end
end

--  初始化格子信息
function UISkyStoneChoose:initGridInfo(grid, data)
    -- 图标
    local focusLight = findChildByName(grid, "focus");
    focusLight:setVisible(false);
    local iconImg = findChildByName(grid, "icon");
    local fileName = ItemM.query(data.classId, "icon");
    iconImg:loadTexture(getItemIconPath(fileName));

    local bg = findChildByName(grid, "bg");
    bg.classId = data.classId;

    -- 星级
    local starNode = findChildByName(grid, "star");
    starNode:setVisible(true);
    starNode:removeAllChildren();

    local lightStarPath = "images/ui/symbol/star_little.png";
    local rankLayer = createStarLayer(data.rank, lightStarPath, "center", -0.25);
    starNode:addChild(rankLayer);

    local numLable = findChildByName(grid, "level_label");
    TextStyleM.setTextStyle(numLable, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    numLable:setVisible(true);
    numLable:setString(data.amount);
end

-- 注册商品点击事件
function UISkyStoneChoose:registerItemTouchEvent(node)
    -- 注册商品图标点击事件
    local bg = node:getChildByName("bg");
    local function onClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");

            if self.data[node.index] == nil then
                return;
            end
            local lastSelected = self.selectIndex;

            self.selectIndex = node.index;

            self:onItemSelected(lastSelected, node.index);
        end
    end
    bg:addTouchEventListener(onClick);
end

-- 注册事件处理回调函数
function UISkyStoneChoose:registerEventCallback()
    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            cclog("UISkyStoneChoose 界面析构清理");
            EventMgr.removeAll("UISkyStoneChoose");

			-- 显示后面的窗口
            local layerForm = tolua.cast(self.backForm,"cc.Node");
            if layerForm then
                self.backForm:setVisible(true);
            end

        elseif eventType == "enter" then
            -- 隐藏后面的窗口
            self.backForm:setVisible(false);
        end
    end);

    -- 关注事件
end

-- 注册点击事件
function UISkyStoneChoose:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UISkyStoneChoose");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

	-- 隐藏中间不用按钮
    local btnRepair = findChildByName(self.node, "BT/repair_btn");
    btnRepair:setVisible(false);

    -- 注册选择按钮点击时间
    local btnSelect = findChildByName(self.node, "BT/choose_btn");
    btnSelect:setVisible(true);
    local function onSelectClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            local data = self.data[self.selectIndex];

			-- 设置当前符石信息
            self.backForm:updateStone(data.classId);

            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UISkyStoneChoose");
        end
    end
    btnSelect:addTouchEventListener(onSelectClick);
    TextStyleM.setTextStyle(btnSelect, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnSelect:setTitleText(getLocStr("btn_text_select"));
end

-- 选中效果
function UISkyStoneChoose:onItemSelected(lastSelected, nowSelected)
    -- 清除上次选中效果
    local lastSel = self.scrollView:getChildByName("item" .. lastSelected);
    local focusBg = lastSel:getChildByName("focus");
    focusBg:setVisible(false);

    -- 新选中的效果
    local nowSel = self.scrollView:getChildByName("item" .. nowSelected);
    local nowFocusBg = nowSel:getChildByName("focus");
    nowFocusBg:setVisible(true);

    -- 更新说明
    local data = self.data[nowSelected];
    self:refreshExplain();
end


-- 设置说明
function UISkyStoneChoose:refreshExplain()
    -- 先把标题和描述隐藏起来
    local captionLabel = findChildByName(self.CT, "bg_2/caption_label");
    captionLabel:setVisible(false);
    TextStyleM.setTextStyle(captionLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_DARK_RED);

    local Label = findChildByName(self.CT, "bg_2/explain_scroll/explain");
    Label:setVisible(false);

    local durabilityLabel = findChildByName(self.CT, "bg_2/durability_label");
    durabilityLabel:setVisible(false);

    local scrapLabel = findChildByName(self.CT, "bg_2/scrap_label");
    scrapLabel:setVisible(false);

    local needScrapLabel = findChildByName(self.CT, "bg_2/need_scrap_label");
    needScrapLabel:setVisible(false);

    -- 阵营
    local campLabel = findChildByName(self.CT, "bg_2/camp_label");
    campLabel:setVisible(false);

    -- 隐藏阵营
    local campIcon = findChildByName(self.CT, "bg_2/camp_icon");
    campIcon:setVisible(false);

    local exLabel = findChildByName(self.CT, "bg_2/explain_scroll/explain");
    exLabel:setVisible(false);
    TextStyleM.setTextStyle(exLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BLUE);

    -- 符石个数
    local totalCount = #self.data;
    if totalCount == 0 then
        captionLabel:setVisible(true);
        exLabel:setVisible(true);

        if self.style == "revenge" then
            applyString(captionLabel, getLocStr("revenge_stone_choose_title"));
            applyString(exLabel, getLocStr("get_revenge_stone_hint"));
        elseif self.style == "plunder" then
            applyString(captionLabel, getLocStr("plunder_stone_choose_title"));
            applyString(exLabel, getLocStr("get_plunder_stone_hint"));
        else
            applyString(captionLabel, getLocStr("explore_stone_choose_title"));
            applyString(exLabel, getLocStr("get_explore_stone_hint"));
        end

        return;
    end

    local data = self.data[self.selectIndex];
    if data == nil then
        print("符石信息显示失败")
        return;
    end

    campLabel:setVisible(true);
    TextStyleM.setTextStyle(campLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_DARK_BROWN);
    applyString(campLabel, string.format(getLocStr("carriable_item_amount"), data.amount));

    captionLabel:setVisible(true);
    applyString(captionLabel, data.name);

    exLabel:setVisible(true);
    applyString(exLabel, data.desc);
end
